<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, Rule, useForm } from '/@/components/Form/index';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { CheckExistParams } from "/@/api/model/baseModel";
import { FormValidPatternEnum } from "/@/enums/constantEnum";

import { personalFormSchema } from './staff.data';
import { getDepts } from '/@/api/org/dept';
import { getCompanies } from '/@/api/org/company';
import { add, update, checkEntityExist } from '/@/api/org/staff';

export default defineComponent({
  name: 'StaffModal',
  components: { BasicModal, BasicForm, PlusOutlined, LoadingOutlined, },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);
    const { createMessage } = useMessage();

    const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
      labelWidth: 100,
      schemas: personalFormSchema,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 23,
      },
    });

    const getBaseDynamicRules = (params: CheckExistParams) => {
      return [
        {
          trigger: 'blur',
          validator: (_, value) => {
            if (value) {
              return checkEntityExist({ id: params.id, field: params.field, fieldValue: value, fieldName: params.fieldName }).then(res => {
                if (res) {
                  return Promise.resolve();
                } else {
                  return Promise.reject(params.fieldName + "已存在，请修改！")
                }
              }).catch((res) => {
                return Promise.reject(res)
              })
            } else {
              return Promise.resolve();
            }
          }
        }
      ] as Rule[];
    }

    const [registerModal, { setModalProps, closeModal, changeLoading }] = useModalInner(async (data) => {
      changeLoading(true);
      resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      const companyTreeData = await getCompanies();
      let formData = data.record;



      await updateSchema([
        {
          field: 'code',
          dynamicRules: () => {
            return [
              {
                required: true,
                whitespace: true,
                message: '工号不能为空！',
              },
              {
                pattern: new RegExp(FormValidPatternEnum.SN),
                type: 'string',
                message: '请输入英文或数字！',
              },
              {
                max: 32,
                message: '字符长度不能大于32！',
              },
              ...getBaseDynamicRules({ id: unref(isUpdate) && formData && formData.id || "", field: 'code', fieldValue: "", fieldName: '工号' }),
            ];
          },
        }
      ]);

      if (unref(isUpdate)) {
        // 根据公司加载部门树
        const deptTreeData = await getDepts({ companyId: data.record.companyId });
        updateSchema([
          {
            field: 'deptId',
            componentProps: { treeData: deptTreeData },
          },
        ]);
        setFieldsValue({
          ...data.record,
        });
      } else {
        // 如果是添加并且用户选择了公司
        if (formData.companyId) {
          // 根据公司加载部门树
          const deptTreeData = await getDepts({ companyId: formData.companyId });
          updateSchema([
            {
              field: 'deptId',
              componentProps: { treeData: deptTreeData },
            },
          ]);
          setFieldsValue({
            ...formData,
          });
        }
      }
      changeLoading(false);
    });

    const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));




    async function handleSubmit() {
      try {
        setModalProps({ confirmLoading: true });
        const values = await validate();
        if (unref(isUpdate))
          await update(values);
        else
          await add(values);
        closeModal();
        emit('success');
      } finally {
        setModalProps({ confirmLoading: false });
      }
    }

    return {
      registerModal, registerForm, getTitle, handleSubmit,
    };
  },
});
</script>
